<!-- 批发市场管理 -->
<template>
  <div>
    <CommonSearch @search="query" @reset="reset">
      <el-col :span="8">
        <el-form-item label="农产品名称">
          <el-input
            v-model="queryParams.condition.produceName"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="价格发布时间">
          <el-date-picker
            v-model="queryParams.condition.searchTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%; height: 33px"
            @change="
              (date) =>
                timeChange(date, queryParams.condition, [
                  'beginTime',
                  'endTime',
                ])
            "
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属批发市场">
          <el-input
            v-model="queryParams.condition.marketName"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属品类" prop="categoryId">
          <QueryCategoryTree
            v-model="queryParams.condition.categoryId"
            :url="api.queryProduceCategoryTree"
            :payload="{}"
            :cascaderProps="{
              children: 'subProduceCategoryList',
              label: 'name',
              value: 'id',
            }"
            clearable
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button @click="add" size="small">新增</el-button>
          <el-button @click="batchImport" size="small">批量导入</el-button>
          <el-button @click="handlerDelete" size="small">批量删除</el-button>
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <edu-table
        ref="mainTable"
        :data="tableList"
        :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum"
        :total="queryParams.total"
        @page-change="handleCurrentChange"
        :order="true"
        :selection="true"
      >
        <el-table-column label="农产品名称" prop="produceName" />
        <el-table-column label="所属批发市场" prop="marketName" />
        <el-table-column label="所属品类" prop="categoryName" />
        <el-table-column
          label="农产品价格"
          prop="price"
          :formatter="rounding"
        />
        <el-table-column label="价格发布时间" prop="pushTime" />

        <el-table-column label="操作" fixed="right" width="150px">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)" size="small">
              编辑
            </el-button>
            <el-button
              type="text"
              @click="handlerDelete(scope.row)"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </edu-table>
    </div>

    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="closeDialog(dialogConfig)"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属农产品" prop="produceId">
              <SelectProduct
                ref="selectProduceId"
                v-model="dialogConfig.formData.produceId"
                v-bind:valueText="dialogConfig.formData.produceName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="dialogConfig.formData.price"
                controls-position="right"
                :min="0"
                clearable
                :step="0.01"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属批发市场" prop="marketId">
              <SelectMarket
                ref="selectMarketId"
                v-model="dialogConfig.formData.marketId"
                v-bind:valueText="dialogConfig.formData.marketName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="pushTime">
              <el-date-picker
                v-model="dialogConfig.formData.pushTime"
                type="datetime"
                style="width: 100%; height: 33px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>

    <!-- 批量导入 -->
    <BatchImport
      ref="batchImport"
      downloadTplUrl="com.iss.edu.service.business.vo.farm.ImportProducePriceVo"
      action="/nongmao/nb-pc/1.0.1/ProducePriceService/importProducePrice"
      @uploadDone="uploadDone"
      @done="query"
    />
  </div>
</template>

<script>
import utils from "@/utils";
import mixins from "@/mixins";

import {
  addProducePrice,
  deleteProducePrice,
  queryProducePriceList,
  updateProducePrice,
  queryProduceCategoryTree,
} from "@/api/market";
import SelectMarket from "./components/SelectMarket";
import SelectProduct from "./components/SelectProduct";

const formData = {
  produceId: "",
  marketId: "",
  price: "",
  pushTime: "",
};

export default {
  mixins: [mixins],
  components: {
    SelectMarket,
    SelectProduct,
  },
  data() {
    return {
      queryParams: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          produceId: [
            {
              required: true,
              message: "此项必填！",
              trigger: "change",
            },
          ],
          price: [
            {
              required: true,
              message: "此项必填！",
              trigger: "change",
            },
          ],
          marketId: [
            {
              required: true,
              message: "此项必填！",
              trigger: "change",
            },
          ],
          pushTime: [
            {
              required: true,
              message: "此项必填！",
              trigger: "change",
            },
          ],
        },
      },
      api: {
        queryProduceCategoryTree,
      },
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    async initOptions() {},
    // 查询
    async query() {
      let { returnObj } = await queryProducePriceList(this.queryParams);
      this.tableList = returnObj.list;
      this.queryParams.total = returnObj.total;
      this.queryParams.pageSize = returnObj.pageSize;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.query();
    },
    // 分页
    handleCurrentChange(row) {
      this.queryParams.pageSize = row.pageSize;
      this.queryParams.pageNum = row.pageNum;
      this.query();
    },
    closeDialog(dialog) {
      dialog.showDialog = false;
      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add() {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";
      this.dialogConfig.formData = utils.clone(formData);
      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.selectProduceId.init();
        this.$refs.selectMarketId.init();
        setTimeout(() => {
          this.$refs["dialogForm"].clearValidate();
        }, 0);
      });
    },
    // 修改
    async edit(row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";
      this.dialogConfig.formData = utils.clone(row);
      this.openDialog(this.dialogConfig);
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
      };
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addProducePrice(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateProducePrice(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    // 查看
    view() {
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      this.openDialog(this.dialogConfig);
    },
    // 批量导入
    async batchImport() {
      this.$refs.batchImport.open();
    },
    uploadDone(data) {
      let msg = [];
      data.map((item, index) => {
        if (item.checkResult) {
          msg.push(`第${index + 1}行 ${item.checkResult}`);
        }
      });

      this.$alert(msg.join("<br/>"), "警告", {
        dangerouslyUseHTMLString: true,
      });
    },
    // 删除
    async handlerDelete(row) {
      let idField = "id";
      if (row && row[idField]) {
        this.batchDelete(deleteProducePrice, idField, [row[idField]]);
      } else {
        this.batchDelete(deleteProducePrice, idField);
      }
    },
    rounding(row, column) {
      return parseFloat(row[column.property]).toFixed(2);
    },
  },
};
</script>

<style lang="scss" scoped></style>
